<template>
  <div class="app-container">
    <el-card shadow="never" class="table-container">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card shadow="never" class="table-container">
            <template #header>
              <div class="flex justify-between">
                <div>
                  <el-button
                    v-hasPerm="['configgroup@add']"
                    @click="openDialog(undefined, 'type-form')"
                    type="success"
                    ><i-ep-plus />新增</el-button
                  >
                </div>
                <div>
                  <!--                <el-button class="ml-3"  icon="Search" circle></el-button>-->
                  <el-button
                    class="ml-3"
                    title="刷新"
                    @click="handleQuery"
                    icon="Refresh"
                    circle
                  />
                </div>
              </div>
            </template>
            <el-table
              ref="singleTable"
              v-loading="loading"
              :data="groups"
              fit
              @row-click="groupTypeChange"
              style="width: 100%"
            >
              <el-table-column label="分组名称" align="center">
                <template #default="scope">
                  <span class="link-type">{{ scope.row.title }}</span
                  >&nbsp;&nbsp;
                  <el-icon size="10" v-if="currentRowId == scope.row.id"
                    ><DArrowRight
                  /></el-icon>
                </template>
              </el-table-column>

              <el-table-column
                label="操作"
                fixed="right"
                align="center"
                width="85"
                class-name="small-padding fixed-width"
              >
                <template #default="scope">
                  <el-button
                    size="small"
                    v-hasPerm="['configgroup@edit']"
                    title="编辑"
                    type="primary"
                    @click="openDialog(scope.row.id, 'type-form')"
                    circle
                    icon="edit"
                  />
                  <el-button
                    size="small"
                    v-hasPerm="['configgroup@del']"
                    title="删除"
                    icon="delete"
                    @click="handleGroupDelete(scope.row.id)"
                    circle
                    type="danger"
                  />
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
        <el-col :span="18">
          <el-card shadow="never" class="table-container">
            <template #header>
              <div class="flex justify-between">
                <div>
                  <el-button
                    v-hasPerm="['config@add']"
                    @click="openDialog(undefined, 'config-form')"
                    type="success"
                    ><i-ep-plus />新增</el-button
                  >
                  <el-button
                    v-if="removeIds.length > 0"
                    v-hasPerm="['config@del']"
                    @click="handleConfigDelete()"
                    type="danger"
                    ><i-ep-delete />删除</el-button
                  >
                </div>
                <div>
                  <div v-if="isShowSearchBtn" style="display: inline-block">
                    <el-form
                      ref="queryFormRef"
                      :model="queryParams"
                      :inline="true"
                    >
                      <el-form-item label="关键字" prop="title">
                        <el-input
                          v-model="queryParams.title"
                          placeholder="名称/编码"
                          clearable
                          style="width: 200px"
                          @keyup.enter="handleConfigQuery"
                        />
                      </el-form-item>

                      <el-form-item label="状态" prop="is_hid">
                        <el-select
                          v-model="queryParams.is_hid"
                          placeholder="全部"
                          clearable
                          class="!w-[100px]"
                        >
                          <el-option label="启用" value="0" />
                          <el-option label="禁用" value="1" />
                        </el-select>
                      </el-form-item>

                      <el-form-item>
                        <el-button type="primary" @click="handleConfigQuery"
                          ><i-ep-search />搜索</el-button
                        >
                        <el-button @click="resetQuery">
                          <i-ep-refresh />
                          重置</el-button
                        >
                      </el-form-item>
                    </el-form>
                  </div>
                  <el-button
                    class="ml-3"
                    icon="Search"
                    circle
                    @click="handleSearchShowBtn"
                  />
                  <el-button
                    class="ml-3"
                    title="刷新"
                    @click="handleConfigQuery"
                    icon="Refresh"
                    circle
                  />
                </div>
              </div>
            </template>
            <el-table
              v-loading="loadingData"
              :data="pageData"
              fit
              @selection-change="handleSelectionChange"
              style="width: 100%"
            >
              <el-table-column align="center" type="selection" />
              <el-table-column label="字典名称" align="left" width="120">
                <template #default="scope">
                  <span
                    class="link-type"
                    @click="openDialog(scope.row.id, 'config-form')"
                    >{{ scope.row.title }}</span
                  >
                </template>
              </el-table-column>
              <el-table-column label="字典编码" align="left" width="130">
                <template #default="scope">
                  <span>{{ scope.row.name }}</span>
                </template>
              </el-table-column>
              <el-table-column label="字典类型" align="center">
                <template #default="scope">
                  <span>{{ scope.row.type }}</span>
                </template>
              </el-table-column>
              <el-table-column label="字典值" align="center">
                <template #default="scope">
                  <span class="overflow">{{ scope.row.value }}</span>
                </template>
              </el-table-column>
              <el-table-column label="字典描述" align="center">
                <template #default="scope">
                  <span class="overflow" :title="scope.row.description">{{
                    scope.row.description
                  }}</span>
                </template>
              </el-table-column>
              <el-table-column label="状态" align="center">
                <template #default="scope">
                  <el-tag
                    effect="dark"
                    :type="scope.row.is_hid == 0 ? 'success' : 'danger'"
                    >{{ scope.row.is_hid == 0 ? "启用" : "禁用" }}</el-tag
                  >
                </template>
              </el-table-column>
              <el-table-column label="排序" align="center">
                <template #default="scope">
                  <span>{{ scope.row.sort }}</span>
                </template>
              </el-table-column>
              <el-table-column label="创建时间" align="center" width="160">
                <template #default="scope">
                  <span>{{ scope.row.created_at }}</span>
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                fixed="right"
                align="center"
                width="120"
                class-name="small-padding fixed-width"
              >
                <template #default="scope">
                  <el-button
                    v-hasPerm="['config@edit']"
                    @click="openDialog(scope.row.id, 'config-form')"
                    title="编辑"
                    type="primary"
                    icon="edit"
                    circle
                  />
                  <el-button
                    v-hasPerm="['config@del']"
                    title="删除"
                    icon="delete"
                    circle
                    type="danger"
                    @click="handleConfigDelete(scope.row.id)"
                  />
                </template>
              </el-table-column>
            </el-table>
            <pagination
              v-if="total > 0"
              v-model:total="total"
              v-model:page="queryParams.p"
              v-model:limit="queryParams.limit"
              @pagination="handleConfigQuery"
            />
          </el-card>
        </el-col>
      </el-row>
    </el-card>
    <!-- 弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      :width="dialog.width"
      append-to-body
      @close="closeDialog"
    >
      <!-- 字典类型新增/编辑表单 -->
      <el-form
        v-if="dialog.type == 'type-form'"
        ref="groupFormRef"
        :model="groupFormData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item style="margin-bottom: 18px" label="字典名称" prop="title">
          <el-input
            v-model="groupFormData.title"
            :readonly="!!groupFormData.id"
            placeholder="请输入字典名称"
          />
        </el-form-item>
        <el-form-item
          style="margin-bottom: 18px"
          label="字典编码"
          prop="table_name"
        >
          <el-input
            v-model="groupFormData.tab_name"
            placeholder="请输入字典编码"
          />
        </el-form-item>
        <el-form-item style="margin-bottom: 18px" label="排序" prop="sort">
          <el-input-number
            v-model="groupFormData.sort"
            controls-position="right"
            :min="0"
          />
        </el-form-item>
        <el-form-item style="margin-bottom: 18px" label="状态" prop="is_hid">
          <el-radio-group v-model="groupFormData.is_hid">
            <el-radio :value="0">正常</el-radio>
            <el-radio :value="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <!-- 字典新增/编辑表单 -->
      <el-form
        v-if="dialog.type == 'config-form'"
        ref="configFormRef"
        :model="configFormData"
        :rules="dictRules"
        label-width="80px"
      >
        <el-form-item style="margin-bottom: 18px" label="字典名称" prop="title">
          <el-input
            v-model="configFormData.title"
            :readonly="!!configFormData.id"
            placeholder="请输入字典名称"
          />
        </el-form-item>
        <el-form-item style="margin-bottom: 18px" label="字典编码" prop="name">
          <el-input
            v-model="configFormData.name"
            placeholder="请输入字典编码"
          />
        </el-form-item>
        <el-form-item
          style="margin-bottom: 18px"
          label="字典类型"
          prop="type"
          placeholder="请选择"
        >
          <el-select
            v-model="configFormData.type"
            placeholder="请选择"
            @change="configType"
          >
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          style="margin-bottom: 18px"
          v-show="configOptionsShow"
          label="配置选项"
          prop="options"
        >
          <el-input
            v-model="configFormData.options"
            placeholder="请输配置选项，值:文字,例如：0:关闭,1开启"
          />
        </el-form-item>
        <el-form-item style="margin-bottom: 18px" label="排序" prop="sort">
          <el-input-number
            v-model="configFormData.sort"
            controls-position="right"
            :min="0"
          />
        </el-form-item>
        <el-form-item
          style="margin-bottom: 18px"
          label="描述"
          prop="description"
        >
          <el-input
            v-model="configFormData.description"
            placeholder="请输入描述"
          />
        </el-form-item>
        <el-form-item style="margin-bottom: 18px" label="状态" prop="is_hid">
          <el-radio-group v-model="configFormData.is_hid">
            <el-radio :value="0">正常</el-radio>
            <el-radio :value="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  getConfigLst,
  getGroupLst,
  configForms,
  configGroupForms,
  delConfig,
  delConfigGroup,
  createConfig,
  createConfigGroup,
  editConfig,
  editConfigGroup,
} from "@/api/config";
import {
  config,
  configForm,
  configGroup,
  configGroupForm,
  configQuery,
} from "@/api/config/types";

const loading = ref(false);
const loadingData = ref(false);
const groups = ref<configGroup[]>();
const pageData = ref<config[]>();
const currentRowId = ref(undefined);
const total = ref(0);
const removeIds = ref([]);
const configOptionsShow = ref(false);
const typeOptions = ref([
  { label: "文本", value: "text" },
  { label: "单选", value: "radio" },
  { label: "文本域", value: "textarea" },
  { label: "图片", value: "image" },
]);
const queryFormRef = ref(ElForm); // 查询表单
const queryParams = reactive<configQuery>({
  p: 1,
  limit: 10,
});
const isShowSearchBtn = ref(false);
const groupFormRef = ref(ElForm); // 用户表单
const configFormRef = ref(ElForm); // 用户表单
const dialog = reactive({
  visible: false,
  type: "type-form",
  width: 800,
  title: "",
});
const groupFormData = reactive<configGroupForm>({
  is_hid: 0,
  sort: 0,
});

const configFormData = reactive<configForm>({
  is_hid: 0,
  sort: 0,
});

const rules = reactive({
  title: [{ required: true, message: "配置组名称不能为空", trigger: "blur" }],
  tab_name: [
    { required: true, message: "配置组编码不能为空", trigger: "blur" },
  ],
});

const dictRules = reactive({
  title: [{ required: true, message: "配置名称不能为空", trigger: "blur" }],
  type: [{ required: true, message: "配置类型不能为空", trigger: "blur" }],
  name: [{ required: true, message: "配置编码不能为空", trigger: "blur" }],
});

function configType(params: any) {
  configOptionsShow.value = params == "radio";
}

//字典类型查询
function handleQuery() {
  loading.value = true;
  getGroupLst()
    .then(({ data }) => {
      groups.value = data;
      queryParams.id = data[0].id;
      currentRowId.value = data[0].id;
      handleConfigQuery();
    })
    .finally(() => {
      loading.value = false;
    });
}
//字典查询
function handleConfigQuery() {
  loadingData.value = true;
  getConfigLst(queryParams)
    .then(({ data }) => {
      pageData.value = data.items;
      total.value = data.total;
    })
    .finally(() => {
      loadingData.value = false;
    });
}

function groupTypeChange(row: any, column: any, event: Event) {
  queryParams.id = row.id;
  currentRowId.value = row.id;
  handleConfigQuery();
}

/** 行选中 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

//删除
function handleGroupDelete(id?: number) {
  ElMessageBox.confirm("确认删除?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    delConfigGroup({ ids: id }).then(() => {
      ElMessage.success("删除成功");
      resetQuery();
    });
  });
}

function handleConfigDelete(id?: number) {
  const ids = id || removeIds.value;
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }
  ElMessageBox.confirm("确认删除?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    delConfig({ ids: ids }).then(() => {
      ElMessage.success("删除成功");
      resetQuery();
    });
  });
}
/**
 * 打开弹窗
 * @param id 用户ID
 */
async function openDialog(id?: number, type?: string) {
  dialog.visible = true;
  if (type) {
    dialog.type = type;
  }
  if (id) {
    dialog.title = "修改";
    if (type == "config-form") {
      configForms(id).then(({ data }) => {
        configOptionsShow.value = data.options == "radio";
        Object.assign(configFormData, { ...data });
      });
    } else {
      configGroupForms(id).then(({ data }) => {
        Object.assign(groupFormData, { ...data });
      });
    }
  } else {
    dialog.title = "新增";
  }
}

const handleSubmit = useThrottleFn(() => {
  if (dialog.type == "type-form") {
    groupFormRef.value.validate((valid: any) => {
      if (valid) {
        const ids = groupFormData.id;
        loading.value = true;
        if (ids) {
          editConfigGroup(groupFormData)
            .then(() => {
              ElMessage.success("修改成功");
              closeDialog();
            })
            .finally(() => (loading.value = false));
        } else {
          createConfigGroup(groupFormData)
            .then(() => {
              ElMessage.success("新增成功");
              closeDialog();
            })
            .finally(() => (loading.value = false));
        }
      }
    });
  } else {
    configFormRef.value.validate((valid: any) => {
      if (valid) {
        configFormData.group_id = queryParams.id;
        const ids = configFormData.id;
        loading.value = true;
        if (ids) {
          editConfig(configFormData)
            .then(() => {
              ElMessage.success("修改成功");
              closeDialog();
            })
            .finally(() => (loading.value = false));
        } else {
          createConfig(configFormData)
            .then(() => {
              ElMessage.success("新增成功");
              closeDialog();
            })
            .finally(() => (loading.value = false));
        }
      }
    });
  }
}, 3000);

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.p = 1;
  handleConfigQuery();
}

//收起展开搜索按钮
function handleSearchShowBtn() {
  isShowSearchBtn.value = isShowSearchBtn.value === false;
}

/**
 * 关闭弹窗
 */
function closeDialog() {
  dialog.visible = false;
  if (dialog.type == "type-form") {
    groupFormRef.value.resetFields();
    groupFormRef.value.clearValidate();
    groupFormData.id = undefined;
    groupFormData.tab_name = "";
    handleQuery();
  } else {
    configFormRef.value.resetFields();
    configFormRef.value.clearValidate();
    configFormData.id = undefined;
    handleConfigQuery();
  }
}
onMounted(() => {
  handleQuery();
});
</script>

<style lang="scss" scoped>
.overflow {
  width: 220px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  -o-text-overflow: ellipsis;
}
.el-form-item {
  margin-bottom: 0px;
}
</style>
